package com.hafu.swing;

import com.hafu.service.CourseService;
import com.hafu.service.LiveClassService;
import com.hafu.service.LiveSessionService;
import com.hafu.service.StudentService;
import com.hafu.service.TeacherService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

// 主界面框架
public class MainFrame extends JFrame {
    private String userId;
    private String role;
    private String username;

    public MainFrame(String userId, String role, String username) {
        this.userId = userId;
        this.role = role;
        this.username = username;
        initUI();
    }

    private void initUI() {
        // 窗口基本设置
        setTitle("网上教育系统 - " + getRoleName(role) + "主界面");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));
        setResizable(false);

        // 顶部面板（标题和用户信息）
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(51, 153, 255));
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        JLabel titleLabel = new JLabel("网上教育系统", JLabel.LEFT);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel, BorderLayout.WEST);

        JLabel userInfoLabel = new JLabel(
                "欢迎您，" + username + " | 角色: " + getRoleName(role) + " | ID: " + userId,
                JLabel.RIGHT
        );
        userInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        userInfoLabel.setForeground(Color.WHITE);
        topPanel.add(userInfoLabel, BorderLayout.EAST);

        // 功能按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(1, 5, 10, 10));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));

        JButton studentButton = createButton("学生管理", new Color(230, 230, 250));
        JButton teacherButton = createButton("教师管理", new Color(240, 248, 255));
        JButton courseButton = createButton("课程管理", new Color(245, 245, 220));
        JButton liveButton = createButton("直播课堂", new Color(255, 240, 245));
        JButton selectButton = createButton("选课管理", new Color(240, 255, 240));

        // 根据角色设置按钮可见性和事件
        if ("student".equals(role)) {
            studentButton.setVisible(false);
            teacherButton.setVisible(false);
            courseButton.addActionListener(e -> openStudentCourseFrame());
            liveButton.addActionListener(e -> openLiveFrame());
            selectButton.addActionListener(e -> openCourseSelectionFrame());
        } else if ("teacher".equals(role)) {
            teacherButton.setVisible(false);
            studentButton.addActionListener(e -> openStudentManagerFrame());
            courseButton.addActionListener(e -> openTeacherCourseFrame());
            liveButton.addActionListener(e -> openLiveFrame());
            selectButton.addActionListener(e -> openStudentCourseManagerFrame());
        } else if ("admin".equals(role)) {
            studentButton.addActionListener(e -> openStudentManagerFrame());
            teacherButton.addActionListener(e -> openTeacherManagerFrame());
            courseButton.addActionListener(e -> openAdminCourseFrame());
            liveButton.addActionListener(e -> openLiveFrame());
            selectButton.addActionListener(e -> openStudentCourseManagerFrame());
        }

        buttonPanel.add(studentButton);
        buttonPanel.add(teacherButton);
        buttonPanel.add(courseButton);
        buttonPanel.add(liveButton);
        buttonPanel.add(selectButton);

        // 底部面板（退出按钮）
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(new Color(230, 230, 230));
        bottomPanel.setBorder(BorderFactory.createEtchedBorder());
        bottomPanel.setPreferredSize(new Dimension(getWidth(), 30));

        JButton exitButton = new JButton("退出系统");
        exitButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        exitButton.addActionListener(e -> {
            int option = JOptionPane.showConfirmDialog(this,
                    "确定要退出系统吗？", "确认退出", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        });
        bottomPanel.add(exitButton);

        // 添加组件到主窗口
        add(topPanel, BorderLayout.NORTH);
        add(buttonPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
        setVisible(true);
    }

    // 创建带样式的按钮
    private JButton createButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setBackground(backgroundColor);
        button.setForeground(new Color(51, 51, 51));
        button.setBorder(BorderFactory.createRaisedBevelBorder());
        button.setPreferredSize(new Dimension(150, 150));
        button.setFocusPainted(false);

        // 鼠标悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent evt) {
                button.setBackground(backgroundColor.darker());
                button.setBorder(BorderFactory.createLoweredBevelBorder());
            }

            @Override
            public void mouseExited(MouseEvent evt) {
                button.setBackground(backgroundColor);
                button.setBorder(BorderFactory.createRaisedBevelBorder());
            }
        });
        return button;
    }

    // 获取角色名称
    private String getRoleName(String role) {
        if ("student".equals(role)) return "学生";
        if ("teacher".equals(role)) return "教师";
        if ("admin".equals(role)) return "管理员";
        return role;
    }

    // 以下是各功能的实际打开逻辑（关键整合点）
    private void openStudentManagerFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("学生管理系统 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            JPanel mainPanel = new JPanel(new BorderLayout());
            frame.setContentPane(mainPanel);

            StudentService studentService = new StudentService();
            DefaultTableModel tableModel = new DefaultTableModel();
            JTable studentTable = new JTable(tableModel);

            // 创建面板后手动初始化内容
            StudentManagePanel studentPanel = new StudentManagePanel(studentService);
            studentPanel.setTableModel(tableModel); // 若有提供该方法
            studentPanel.setTable(studentTable);   // 若有提供该方法

            frame.add(studentPanel);
            frame.setVisible(true);
        });
    }


    private void openTeacherManagerFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("教师管理系统 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            TeacherService teacherService = new TeacherService();
            TeacherManagePanel teacherPanel = new TeacherManagePanel((JPanel) frame.getContentPane(), teacherService);
            frame.add(teacherPanel);

            frame.setVisible(true);
        });
    }

    private void openAdminCourseFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("课程管理系统 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            CourseService courseService = new CourseService();
            JPanel contentPanel = (JPanel) frame.getContentPane(); // 显式转换为 JPanel
            CourseManagePanel coursePanel = new CourseManagePanel(contentPanel, courseService);
            frame.add(coursePanel);

            frame.setVisible(true);
        });
    }

    private void openTeacherCourseFrame() {
        openAdminCourseFrame(); // 教师课程管理与管理员类似，可复用界面
    }

    private void openStudentCourseFrame() {
        SwingUtilities.invokeLater(() -> new StudentMainFrame(userId));
    }

    private void openLiveFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("直播课堂 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            // 修正：使用LiveClassService并只传递两个参数
            LiveClassService liveService = new LiveClassService();
            JPanel contentPanel = new JPanel(new BorderLayout());
            LiveClassPanel livePanel = new LiveClassPanel(contentPanel, liveService);

            frame.setContentPane(contentPanel);
            frame.add(livePanel);

            frame.setVisible(true);
        });
    }

    private void openCourseSelectionFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("选课管理 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            CourseService courseService = new CourseService();
            JPanel contentPanel = new JPanel(new BorderLayout());
            CourseSelectionPanel selectionPanel = new CourseSelectionPanel(contentPanel, courseService, userId);

            frame.setContentPane(contentPanel);
            frame.add(selectionPanel);

            frame.setVisible(true);
        });
    }

    private void openStudentCourseManagerFrame() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("学生选课管理 - " + userId);
            frame.setSize(900, 600);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setLocationRelativeTo(this);

            CourseService courseService = new CourseService();
            JPanel contentPanel = new JPanel(new BorderLayout());
            CourseSelectionPanel selectionPanel = new CourseSelectionPanel(contentPanel, courseService, userId);

            frame.setContentPane(contentPanel);
            frame.add(selectionPanel);

            frame.setVisible(true);
        });
    }
}